/**
 * @author qiuny
 * @description 移动画布内容和缩放元素插件
 * @class
 * @see {@link CoverEditor}
 */

class MoveZoomPlugin {
    // static events = ["mouseDownUpdate", "mouseMoveUpdate", 'mouseDblclickUpdate'];

    constructor (canvas, editor) {
        this.canvas = canvas
        this.editor = editor
        this.lastPositionX = 0;
        this.lastPositionY = 0;
        this.isEnbleDragging = false;
        this._init () 
    }

    _init () {
        this.canvas.on('mouse:wheel', (evt) => this._initMouseWheel(evt));
        this.canvas.on('mouse:down', (evt) => this._initMouseDown(evt));
        this.canvas.on('mouse:move', (evt) => this._initMouseMove(evt));
        this.canvas.on('mouse:up', (evt) => this._initMouseUp(evt));
        this.canvas.on('mouse:dblclick', (evt) => this._initMouseDblclick(evt));
    }

    _initMouseWheel (opt) {
        let delta = opt.e.deltaY;
        let zoom = this.canvas.getZoom();
        zoom *= 0.999 ** delta;
        if (zoom > 20) zoom = 20;
        if (zoom < 0.01) zoom = 0.01;
        this.canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
        opt.e.preventDefault();
        opt.e.stopPropagation();
    }

    _initMouseDown (opt) {
        opt.e.preventDefault();
        opt.e.stopPropagation();
        let evt = opt.e
        if (evt.altKey === true) {
            this.isEnbleDragging = true;
            this.lastPositionX = evt.clientX;
            this.lastPositionY = evt.clientY;
            this.canvas.setCursor('grab')
        }
    }

    // ALT + Drag
    _initMouseMove (opt) {
        if (this.isEnbleDragging) {
            const e = opt.e
            const vpt = this.canvas.viewportTransform;
            vpt[4] += e.clientX - this.lastPositionX;
            vpt[5] += e.clientY - this.lastPositionY;
            this.canvas.requestRenderAll();
            this.lastPositionX = e.clientX;
            this.lastPositionY = e.clientY;
        }
    }

    _initMouseUp (opt) {
        // on mouse up we want to recalculate new interaction
        // for all objects, so we call setViewportTransform
        this.canvas.setViewportTransform(this.canvas.viewportTransform);
        this.isEnbleDragging = false;
    }

    _initMouseDblclick (opt) {
    }


    destroy() {
        console.log('MoveZoomPlugin destroy');
    }

}

export default MoveZoomPlugin;